package net.bithappens.hnqe.impl.rest;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Properties;

import javax.ws.rs.core.UriBuilder;

import net.bithappens.hnqe.impl.HNQE;
import net.bithappens.hnqe.impl.rest.handler.RootResource;

import org.apache.log4j.Logger;

import com.sun.jersey.api.container.httpserver.HttpServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.net.httpserver.HttpServer;

public class HNQERestServer {
	
	private static Logger log = Logger.getLogger(HNQERestServer.class);

	public static void main(String[] args) throws Exception {

		log.info("Starting HNQE rest server");
				
		URL url = ClassLoader.getSystemResource("hnqe.properties");
		Properties properties = new Properties();
		InputStream propertyStream = url.openStream();
		properties.load(propertyStream);
		propertyStream.close();
		
//		File file = new File("./jars/impl/hnqe.properties");	
//		Properties properties = new Properties();
//		InputStream fis = new FileInputStream(file); 
//		properties.load(fis);
//		fis.close();
		
		String restUrl = properties.getProperty("hnqe.rest.url");
		
		int restPort = Integer.valueOf(properties.getProperty("hnqe.rest.port"));
		
		URI restUri = UriBuilder.fromUri(restUrl).port(restPort).build();
		
		
		ResourceConfig resourceConfig = new PackagesResourceConfig(
				"javax.ws.rs.Application",
				"net.bithappens.hnqe.impl.rest.handler",
				"net.bithappens.hnqe.impl.rest.provider");
		
		
		HNQE hnqe = new HNQE();
		
		hnqe.startFrameWork();
		
		RootResource.setHnqe(hnqe);
				
		HttpServer httpServer = HttpServerFactory.create(restUri, resourceConfig);
		
		httpServer.start();
		
		log.info("HNQE started and is available at "+ restUri.toString() +"  -   Hit enter to stop it...");
		System.in.read();
		log.info("Shutting down the HNQE Server");
		
		httpServer.stop(0);
		
		hnqe.stopFrameWork();
		
	}

}
